package com.jelly.config.shiro.filter;

import com.jelly.common.constant.CodeConstant;
import com.jelly.common.constant.Constant;
import com.jelly.common.util.StringUtils;
import com.jelly.common.util.web.WebUtilsPro;
import com.jelly.config.shiro.token.TokenUtil;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * <h4>功能:【验证码拦截】【创建人：QIAOLIANG】</h4>
 *
 * @时间:2018/7/5 0005 9:34
 * @备注:<h4></h4>
 */
public class VcodeFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String code = httpServletRequest.getParameter(CodeConstant.GIFCODE);
        // 拦截当前request请求 是否为ajax请求
        if (WebUtilsPro.isAjaxRequest((HttpServletRequest) servletRequest)) {

            if(StringUtils.isNotBlank(code)){
                //转化成小写字母
                code = code.toLowerCase();
                String sessionVcode = (String) TokenUtil.getSession().getAttribute(CodeConstant.GIFCODESESSION+httpServletRequest.getSession().getId());

                if(code.equals(sessionVcode)){
                    return true;
                }
            }

        }

        return false;

    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {

        servletRequest.setAttribute(CodeConstant.GIFCODE,CodeConstant.GIFCODEERROR);
        return true;
    }
}
